import React, { useEffect, useState } from 'react'
import './searchmusic.scss'
import { LeftOutlined, HomeFilled, SearchOutlined, PlayCircleOutlined, DeleteOutlined } from '@ant-design/icons'
import axios from 'axios'
import { useRef } from 'react'
export default function Searchmusic(props) {
  useEffect(() => {
    getHotSearchList()
    if(props.location.state.searchkey){
      getSearchlist(props.location.state.searchkey)
    }
  // eslint-disable-next-line
  }, [])
  let [hotlist, sethotlist] = useState([])
  let [currentpg, setcurrentpg] = useState(0)
  let [currentSearch, setcurrentSearch] = useState([])
  let [schall, setschall] = useState([])
  let [historyRecord, setHistoryRecord] = useState(JSON.parse(localStorage.getItem('historyRecord')) || [])
  let keyref = useRef(null)
  let [searchkey, setSearchkey] = useState('')
  // 热搜榜
  const getHotSearchList = async () => {
    let { data: { data: hotsearch } } = await axios.get('http://localhost:3000/search/hot/detail')
    sethotlist(hotsearch)
  }
  // 输入框内容改变触发
  const inputChange = async (value) => {
    if (!value) return setcurrentpg(0)
    setcurrentpg(1)
    let { data: { result: { allMatch: search } } } = await axios.get(`http://localhost:3000/search/suggest?keywords=${value}&type=mobile`)
    if (search === undefined) search = []
    setcurrentSearch(search)
  }
  // 搜索列表
  const getSearchlist = async (key) => {
    setSearchkey(key)
    getHistory(key)
    let { data: { result: { songs: searchdata } } } = await axios.get(`http://localhost:3000/search?keywords=${key}`)
    if(searchdata === undefined) searchdata = []
    setschall(searchdata)
    setcurrentpg(2)
    document.querySelector('.schinputdom').value = key
  }

  // 处理多个作者合并
  let getauthor = (data) => {
    let author = []
    data.forEach(item => {
        author.push(item.name)
    })
    return author.join('/')
  }

  let getHistory = (data) => {
    if (data.length){
      let newrecord = Object.assign([], historyRecord)
      let idx = newrecord.findIndex(item=>item===data)
      if (idx !== -1) newrecord.splice(idx, 1)
      newrecord.unshift(data)
      if(newrecord.length >= 10) newrecord.pop()
      setHistoryRecord(newrecord)
      localStorage.setItem('historyRecord', JSON.stringify(newrecord))
    }
  }

let getmusicdetail = async (id) => {
  let {data:{songs:[data]}} = await axios('http://localhost:3000/song/detail?ids='+id)
  let data2 = JSON.parse(JSON.stringify(data))
  delete data2.id
  props.history.push({pathname:"/musicdetail2", state:{...data2, id, searchkey}})
}

  return (
    <div className='searchmusic'>
      <div className='locationBtn'>
        <div><LeftOutlined style={{ color: "#fff", fontSize: "0.2rem" }} onClick={() => { props.history.goBack() }} /></div>
        <div className='fenge'></div>
        <div><HomeFilled style={{ color: "#fff", fontSize: "0.2rem" }} onClick={() => { props.history.push('/') }} /></div>
      </div>
      <div className='searchtitle'>搜索</div>
      <div className='schinputdiv'>
        <input 
        type="text" 
        className='schinputdom'
        placeholder="搜索歌曲"
        onChange={(e) => inputChange(e.target.value)}
        onFocus={(e) => inputChange(e.target.value)}
        ref={keyref}
        />
      </div>
      <div className='searchlist'>
        {
          (historyRecord.length !== 0 && currentpg === 0) && (
            <div className='historyRecord'>
              <div className='recordtitle'>
                <span>历史记录</span>
                <DeleteOutlined onClick={()=>{localStorage.setItem('historyRecord', JSON.stringify([]))}}/>
              </div>
              <div className='histlist'>
                {
                  historyRecord.map(item => {
                    return(
                      <span className='historyitem' key={item} onClick={()=>getSearchlist(item)}>{item}</span>
                    )
                  })
                }
              </div>
            </div>
          )
        }
        {
          currentpg === 0 && (
            <div className='hotsearch'>
              <div className='hottitle'>热搜榜</div>
              <div className='hotlist'>
                {
                  hotlist.map((item, index) => {
                    return (
                      <div className='hotitem' key={item.searchWord} onClick={()=>getSearchlist(item.searchWord)}>
                        <div className='name'>
                          <div className='index' style={{ color: index < 3 ? 'red' : '#999999' }}>
                            {index + 1 < 10 && (<span>&nbsp;&nbsp;</span>)}{index + 1}
                          </div>
                          <div className='title'>
                            <div className='hottitle'>
                              {item.searchWord}
                              {
                                index === 0 && (<span className='first'>HOT</span>)
                              }
                            </div>
                            <div className='desc'>
                              {item.content}
                            </div>
                          </div>
                        </div>
                        <div className='score'><span>{item.score}</span></div>
                      </div>

                    )
                  })
                }
              </div>
            </div>
          )
        }
        {
          currentpg === 1 && (
            <div className='searchkey'>
              <div className='btn' onClick={()=>getSearchlist(keyref.current.value)}>
                搜索“{keyref.current.value}”
              </div>
              {
                currentSearch.map((item) => {
                  return (
                    <div key={item.keyword} className="currschitem"  onClick={()=>getSearchlist(item.keyword)}>
                      <SearchOutlined style={{ color: "#BCBCBC", paddingRight: "0.1rem", fontSize: "0.22rem" }} />{item.keyword}
                    </div>
                  )
                })
              }
            </div>
          )
        }
        {
          currentpg === 2 && (
            <div className='searchall'>
              {
                schall.map(item => {
                  return (
                    <div key={item.id} className="schallitem" onClick={()=>getmusicdetail(item.id)}>
                      <div className='name'>
                        <div className='title'>
                          {item.name}
                        </div>
                        <div className='desc'>
                          {getauthor(item.artists)}-{item.album.name}
                        </div>
                      </div>
                      <div className='bofang'>
                        <PlayCircleOutlined style={{fontSize:"0.25rem",color:"#ccc",marginTop:"0.1rem"}}/>
                      </div>
                    </div>
                  )
                })
              }
            </div>
          )
        }
      </div>
    </div>
  )
}
